﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Tracker.Data.Repository;
using Tracker.Data.UnitOfWork;
using Tracker.Domain.Entities;
using Tracker.Domain.DTOs;
using Tracker.Services.Abstract;
using SimpleCrypto;

namespace Tracker.Services.Implementation
{
    public class UserService : Service<User>, IUserService
    {
        private readonly ICryptoService _cryptoService;

        public UserService(IRepository<User> repository, IUnitOfWork unitOfWork)
            : base(repository, unitOfWork)
        {
            _cryptoService = new SimpleCrypto.PBKDF2();
        }

        public void Add(UserDTO dto)
        {
            var user = new User();
            user.Username = dto.Username;
            user.Salt = _cryptoService.GenerateSalt();
            user.Password = _cryptoService.Compute(dto.Password, user.Salt);
            user.InsertDate = DateTime.Now;
            user.ModifiedDate = DateTime.Now;
            dto.ID = base.Add(user);
        }

        public void Update(UserDTO dto)
        {
            throw new NotImplementedException();
        }

        public UserDTO Get(int id)
        {
            throw new NotImplementedException();
        }

        public UserDTO Get(Expression<Func<User, bool>> predicate)
        {
            throw new NotImplementedException();
        }

        public IList<UserDTO> GetAll()
        {
            throw new NotImplementedException();
        }

        public IList<UserDTO> GetAll(Expression<Func<User, bool>> predicate)
        {
            throw new NotImplementedException();
        }

        public UserDTO Login(UserDTO dto)
        {
            var user = base.Single(x => x.Username.ToLower() == dto.Username.ToLower());

            if (user != null && user.Password == _cryptoService.Compute(dto.Password, user.Salt))
            {
                dto.ID = user.ID;
                dto.Email = user.Email;
                dto.InsertDate = user.InsertDate;
                dto.ModifiedDate = user.ModifiedDate;
                return dto;
            }

            return null;
        }
    }
}
